<template>
  <div class="container">
    <!-- 左侧 模型信息 -->
    <div class="info-panel">
      <h2>模型信息</h2>
      <div v-if="selectedModel">
        <p><strong>名称:</strong> {{ selectedModel.name || '未命名模型' }}</p>
        <p><strong>颜色:</strong> {{ selectedModel.material.color.getHexString() }}</p>
        <!-- 其他相关模型信息 -->
      </div>
      <div v-else>
        <p>点击右侧模型以显示信息。</p>
      </div>
    </div>

    <!-- 右侧 3D 模型预览 -->
    <div ref="sceneContainer" class="preview-panel" />
  </div>
</template>

<script>
import * as THREE from 'three'

export default {
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      raycaster: null,
      mouse: new THREE.Vector2(),
      objects: [],
      selectedModel: null // 选中的模型
    }
  },
  mounted() {
    this.initScene()
    this.animate()
    // setInterval(() => {
    //   this.goToNextPage()
    // },5000)
  },
  beforeDestroy() {
    window.removeEventListener('click', this.onMouseClick)
  },
  methods: {
    initScene() {
      // 创建场景
      this.scene = new THREE.Scene()

      // 创建相机
      this.camera = new THREE.PerspectiveCamera(
        75,
        this.$refs.sceneContainer.clientWidth / this.$refs.sceneContainer.clientHeight,
        0.1,
        1000
      )
      this.camera.position.z = 5

      // 创建渲染器
      this.renderer = new THREE.WebGLRenderer()
      this.renderer.setSize(
        this.$refs.sceneContainer.clientWidth,
        this.$refs.sceneContainer.clientHeight
      )
      this.$refs.sceneContainer.appendChild(this.renderer.domElement)

      // 创建模型
      this.addCube()

      // 创建 Raycaster 用于点击检测
      this.raycaster = new THREE.Raycaster()

      // 监听点击事件
      window.addEventListener('click', this.onMouseClick)
    },
    addCube() {
      const geometry = new THREE.BoxGeometry()
      const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
      const cube = new THREE.Mesh(geometry, material)
      cube.name = '立方体' // 设置模型名称
      this.scene.add(cube)
      this.objects.push(cube) // 将模型添加到可点击数组中
    },
    onMouseClick(event) {
      // 将鼠标坐标标准化为归一化设备坐标（NDC）
      this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1
      this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1

      // 使用 Raycaster 检测点击的对象
      this.raycaster.setFromCamera(this.mouse, this.camera)
      const intersects = this.raycaster.intersectObjects(this.objects)

      if (intersects.length > 0) {
        const object = intersects[0].object
        this.selectedModel = object // 设置当前点击的模型信息
      }
    },
    animate() {
      requestAnimationFrame(this.animate)
      this.renderer.render(this.scene, this.camera)
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
}

.info-panel {
  width: 30%;
  padding: 20px;
  background-color: #f4f4f4;
  overflow-y: auto;
}

.preview-panel {
  width: 70%;
  height: 100vh;
  background-color: #ddd;
}
</style>
